<template>
  <div class="dashboard-container">
    <div class="left-container">
      <!-- 左侧顶部 - 诊所基本信息 -->
      <div class="left-top">
        <div class="left-top-header">
          <div class="clinic-logo">
            <img src="https://img1.baidu.com/it/u=3188450033,2107785254&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500"
                 alt="诊所logo">
          </div>
          <div class="current-time">
            <div class="time-weather">
              <span class="date">{{ currentDate }}</span>
              <span class="weather" v-if="weatherInfo">
				 <i :class="weatherInfo.icon"></i>
				 {{ weatherInfo.text }} {{ weatherInfo.temp }}℃
			   </span>
            </div>
            <div class="greeting">{{ greeting }}</div>
          </div>

        </div>
        <div class="left-top-bottom">
          <el-card class="clinic-info-card">
            <div class="info-item">
              <span class="label">诊所名称：</span>
              <span class="value">{{ clinicInfo.name }}</span>
            </div>
            <!--  <div class="info-item">
                <span class="label">诊所地址：</span>
                <span class="value">{{ clinicInfo.address }}</span>
              </div>
              <div class="info-item">
                <span class="label">诊所编码：</span>
                <span class="value">{{ clinicInfo.code }}</span>
              </div> -->
          </el-card>

          <!-- 日历组件 -->
          <div class="calendar-container">
            <div class="calendar-header">
              <!-- <span>{{ calendarYearMonth }}</span> -->
              <!-- 在calendar-container中添加时间区间选择器 -->
              <div class="calendar-container">

                <div class="calendar-header">
                  <div class="date-range-selector">
                    <el-date-picker
                        v-model="dateRange"
                        type="daterange"
                        align="right"
                        unlink-panels
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :picker-options="pickerOptions"
                        size="small"
                        @change="handleDateRangeChange"
                    ></el-date-picker>
                  </div>
                </div>
                <div class="calendar-days">
                  <!--  <el-calendar>
                      <template
                        slot="dateCell"
                        slot-scope="{date, data}">
                        <p :class="data.isSelected ? 'is-selected' : ''">
                          {{ data.day.split('-').slice(1).join('-') }} {{ data.isSelected ? '✔️' : ''}}
                        </p>
                      </template>
                    </el-calendar> -->
                </div>
              </div>
            </div>
            <!-- <div class="calendar-week">
              <div v-for="day in weekDays" :key="day" class="week-day">{{ day }}</div>
            </div> -->
            <div class="calendar-days">
              <el-calendar>
                <template
                    slot="dateCell"
                    slot-scope="{date, data}">
                  <div
                      :class="['calendar-day', { 'is-selected': data.isSelected, 'is-signed': isDateSigned(data.day) }]">
                    {{ data.day.split('-').slice(1).join('-') }}
                    <i v-if="isDateSigned(data.day)" class="el-icon-success signed-icon"></i>
                  </div>
                </template>
              </el-calendar>
            </div>
            <!-- 挂号人次和就诊人次 -->
            <div class="double-chart-container">
              <el-card class="half-chart-card">
                <div class="chart-header">
                  <div class="chart-title">挂号人次</div>
                  <div class="chart-filters">
                    <el-select v-model="registerFilter" placeholder="请选择" size="small">
                      <el-option
                          v-for="item in registerOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                      </el-option>
                    </el-select>
                  </div>
                </div>
                <div class="chart-wrapper">
                  <div ref="registerChart" class="chart" style="height: 250px;"></div>
                </div>
              </el-card>

              <el-card class="half-chart-card">
                <div class="chart-header">
                  <div class="chart-title">就诊人次</div>
                  <div class="chart-filters">
                    <el-select v-model="visitFilter" placeholder="请选择" size="small">
                      <el-option
                          v-for="item in visitOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                      </el-option>
                    </el-select>
                  </div>
                </div>
                <div class="chart-wrapper">
                  <div ref="visitChart" class="chart" style="height: 250px;"></div>
                </div>
              </el-card>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="right-container">
      <!-- 右侧顶部 - 6个数据卡片 -->
      <div class="stats-cards">
        <el-card
            v-for="(card, index) in statCards"
            :key="index"
            class="stat-card"
            @click.native="handleCardClick(index)"
            :style="{ 'animation-delay': `${index * 0.1}s` }"
        >
          <div class="df">
            <div class="card-icon" :style="{ backgroundColor: card.color }">
              <i :class="card.icon"></i>
            </div>
            <div class="card-content">
              <div class="card-title">{{ card.title }}</div>
              <div class="card-value">{{ card.value }}</div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 费用占比饼图 -->
      <div class="chart-container">
        <el-card class="chart-card">
          <div class="chart-header">
            <div class="chart-title">费用占比</div>
            <div class="chart-filters">
              <el-date-picker
                  v-model="expenseDateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  size="small"
                  :default-value="defaultDateRange"
                  :picker-options="pickerOptionsII">
              </el-date-picker>
            </div>
          </div>
          <div class="chart-wrapper">
            <div ref="expenseChart" class="chart" style="height: 300px;"></div>
          </div>
        </el-card>
      </div>
      <!-- 收入趋势折线图 -->
      <div class="chart-container">
        <el-card class="chart-card">
          <div class="chart-header">
            <div class="chart-title">收入趋势</div>
            <div class="chart-filters">
              <el-select v-model="incomeTrendFilter" placeholder="请选择" size="small">
                <el-option
                    v-for="item in incomeTrendOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="chart-wrapper">
            <div ref="incomeTrendChart" class="chart" style="height: 300px;"></div>
          </div>
        </el-card>
      </div>


    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {statist} from "@/api/index.js";

export default {
  name: 'Dashboard',
  data() {
    return {
      // 当前日期和时间
      currentDate: '',
      currentTime: '',
      currentWeekDay: '',
      weatherInfo: null,
      greeting: '',

      // 日历数据
      calendarYearMonth: '2025年7月',
      weekDays: ['日', '一', '二', '三', '四', '五', '六'],
      calendarDays: [
        {day: 26, isToday: true, status: '正常'},
        {day: 27, status: '正常'},
        {day: 28, status: '正常'},
        {day: 29},
        {day: 30},
        {day: 31, isOtherMonth: true},
        {day: 1, isOtherMonth: true},
        // ... 更多日期数据
      ],
      // 新增日期范围数据
      dateRange: [],
      pickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const end = new Date();
              end.setDate(end.getDate() - 1);
              const start = new Date(end);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '一周前',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setDate(start.getDate() - 7);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '一个月前',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 1);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '三个月前',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 3);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '半年前',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 6);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '一年前',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setFullYear(start.getFullYear() - 1);
              picker.$emit('pick', [start, end]);
            }
          }
        ]
      },
      // 统计卡片数据
      statCards: [
        {icon: 'el-icon-chargingPrice', title: '西药处方金额', value: '37', color: '#409EFF', index: 1},
        {icon: 'el-icon-qjtyw', title: '西药处方数量', value: '120', color: '#67C23A', index: 2},
        {icon: 'el-icon-navicon-kcz', title: '挂号金额', value: '¥5,600', color: '#E6A23C', index: 3},
        {icon: 'el-icon-ghlb', title: '挂号人次', value: '98', color: '#F56C6C', index: 4},
        {icon: 'el-icon-blsjxj', title: '处方金额', value: '¥12,800', color: '#909399', index: 5},
        {icon: 'el-icon-bzdw', title: '处方数量', value: '42%', color: '#B37FEB', index: 6},
        {icon: 'el-icon-mzy', title: '中药处方金额', value: '120', color: '#67C23A', index: 7},
        {icon: 'el-icon-ddzy', title: '中药处方数量', value: '37', color: '#409EFF', index: 8},
        {icon: 'el-icon-zhifubao', title: '就诊收费金额', value: '¥5,600', color: '#409EFF', index: 9},
        {icon: 'el-icon-flxz', title: '就诊收费人次', value: '98', color: '#F56C6C', index: 10},
        {icon: 'el-icon-dangan', title: '就诊人次', value: '¥12,800', color: '#909399', index: 11},
        {icon: 'el-icon-lcyt', title: '药占比', value: '42%', color: '#B37FEB', index: 12},

      ],
      signedDates: [],
      // 收入趋势筛选
      incomeTrendFilter: 'all',
      incomeTrendOptions: [
        {value: 'all', label: '全部'},
        {value: 'register', label: '挂号金额'},
        {value: 'charge', label: '就诊收费金额'},
        {value: 'western', label: '西药处方金额'},
        {value: 'chinese', label: '中药处方金额'}
      ],
      clinicId: 0,
      // 挂号人次筛选
      registerFilter: 'all',
      registerOptions: [
        {value: 'all', label: '全部'},
        {value: 'appointment', label: '预约挂号人次'},
        {value: 'onsite', label: '现场挂号人次'}
      ],

      // 就诊人次筛选
      visitFilter: 'all',
      visitOptions: [
        {value: 'all', label: '全部'},
        {value: 'appointment', label: '预约就诊人次'},
        {value: 'onsite', label: '现场就诊人次'}
      ],

      // 费用占比日期范围
      expenseDateRange: [],
      defaultDateRange: [new Date(2024, 2, 1), new Date(2024, 2, 7)],
      pickerOptionsII: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      apiData: {},
      clinicInfo: {
        name: '',
        address: '',
        code: ''
      },
      // ECharts 实例
      incomeTrendChart: null,
      registerChart: null,
      visitChart: null,
      expenseChart: null
    };
  },
  // 在mounted方法中添加诊所信息赋值
  mounted() {
    this.updateCurrentDateTime();
    setInterval(this.updateCurrentDateTime, 1000);

    this.userInfo = JSON.parse(localStorage.getItem('userInfo')) || {};
    this.clinicId = this.userInfo.clinicId;

    // 更安全的 signedDates 初始化
    this.signedDates = this.getSafeSignedDates();

    // 设置诊所基本信息
    this.clinicInfo = {
      name: this.userInfo.clinicName || '宜宾九阵诊所',
      address: this.userInfo.clinicAddress || '三江新区邦泰国际数据中心888号',
      code: this.userInfo.clinicCode || 'JZ-2025-0729'
    };

    // 设置默认日期范围为今天
    const today = new Date();
    this.dateRange = [today, today];

    this.initWeather();

    // 调用接口时传入今天的日期范围
    this.fetchStatisticsData(today, today)
        .then(() => {
          this.$nextTick(() => {
            this.initChartsWithApiData();
          });
        })
        .catch(error => {
          console.error('初始化数据失败:', error);
        });

    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);

    // 清理所有图表实例
    [this.incomeTrendChart, this.registerChart, this.visitChart, this.expenseChart].forEach(chart => {
      try {
        if (chart) {
          chart.dispose();
          chart = null;
        }
      } catch (error) {
        console.error('销毁图表实例失败:', error);
      }
    });
  },
  methods: {
    handleCardClick(index) {
      console.log(index, 'indexindexindexindex')
      switch (index) {
        case 0 :
          this.$router.push('/reservation/westernMedicineList/westernMedicineList')
          break;

        case 1 :
          this.$router.push('/reservation/westernMedicineList/westernMedicineList')
          break;
        case 6 :
          this.$router.push('/reservation/chinaMedicineList/chinaMedicineList')
          break;
        case 7 :
          this.$router.push('/reservation/chinaMedicineList/chinaMedicineList')
          break;
      }
    },
    // 安全获取 signedDates 数据
    getSafeSignedDates() {
      try {
        const signedDatesStr = localStorage.getItem('signedDates');
        if (!signedDatesStr) return [];

        // 检查是否是数组格式
        if (signedDatesStr.startsWith('[') && signedDatesStr.endsWith(']')) {
          return JSON.parse(signedDatesStr);
        }

        // 如果是单个日期字符串，转换为数组
        if (/^\d{4}-\d{2}-\d{2}$/.test(signedDatesStr)) {
          return [signedDatesStr];
        }

        // 其他情况返回空数组
        return [];
      } catch (e) {
        console.error('解析 signedDates 失败:', e);
        return [];
      }
    },
    // 获取统计数据
    fetchStatisticsData(startDate, endDate) {
      // 如果没有传入日期参数，使用默认的今天
      if (!startDate || !endDate) {
        const today = new Date();
        startDate = today;
        endDate = today;
      }

      const formatDate = (date) => {
        const pad = num => num.toString().padStart(2, '0');
        return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} 00:00:00`;
      };

      return statist({
        clinicId: this.clinicId,
        startTime: formatDate(startDate),
        endTime: formatDate(endDate)
      }).then(res => {
        if (res.code === 200) {
          // 检查数据是否为字符串，如果是则尝试解析
          let apiData = res.data;
          if (typeof apiData === 'string') {
            try {
              apiData = JSON.parse(apiData);
            } catch (error) {
              console.error('解析API数据失败:', error);
              throw new Error('解析统计数据失败');
            }
          }

          this.apiData = apiData;
          this.initChartsWithApiData();
          this.updateStatCards();
          return apiData;
        } else {
          this.$message.error(res.message || '获取统计数据失败');
          throw new Error(res.message || '获取统计数据失败');
        }
      }).catch(err => {
        console.error('获取统计数据失败:', err);
        this.$message.error('获取统计数据失败');
        throw err;
      });
    },

    // 判断日期是否已签到
    isDateSigned(dateString) {
      return this.signedDates.includes(dateString.split(' ')[0]);
    },

    // 处理日期范围变化
    handleDateRangeChange(val) {
      if (val && val.length === 2) {
        this.fetchStatisticsData(val[0], val[1]);
      }
    },

    // 使用API数据初始化图表
    initChartsWithApiData() {
      if (!this.apiData) {
        // 如果没有API数据，使用默认数据
        this.useDefaultChartData();
        return;
      }

      // 收入趋势折线图
      this.initIncomeTrendChart();

      // 挂号人次柱状图
      this.initRegisterChart();

      // 就诊人次柱状图
      this.initVisitChart();

      // 费用占比饼图
      this.initExpenseChart();
    },

    // 使用默认图表数据
    useDefaultChartData() {
      // 默认日期范围（最近7天）
      const defaultDates = this.generateDefaultDates(7);

      // 设置默认API数据结构
      this.apiData = {
        incomeTrend: {
          dates: defaultDates,
          registerAmounts: [1200, 1400, 1000, 1600, 1800, 1500, 2000],
          chargeAmounts: [3200, 2800, 3500, 3000, 3800, 4200, 4000],
          westernAmounts: [1800, 1600, 2000, 2200, 2400, 2000, 2500],
          chineseAmounts: [800, 700, 900, 750, 850, 900, 950]
        },
        registerTrend: {
          dates: defaultDates,
          appointmentCounts: [45, 50, 40, 55, 60, 50, 65],
          onsiteCounts: [30, 35, 25, 40, 45, 35, 50]
        },
        visitTrend: {
          dates: defaultDates,
          appointmentCounts: [40, 45, 35, 50, 55, 45, 60],
          onsiteCounts: [25, 30, 20, 35, 40, 30, 45]
        },
        expenseRatio: {
          registerFee: 35,
          examFee: 25,
          treatmentFee: 20,
          westernMedicineFee: 15,
          chineseMedicineFee: 5
        },
        // 其他统计数据的默认值
        drugRxMoney: 12800,
        drugRxNum: 120,
        regMoney: 5600,
        regNum: 98,
        rxMoney: 12800,
        rxNum: 42,
        tcmRxMoney: 5600,
        tcmRxNum: 37,
        visitChargeMoney: 5600,
        visitChargeNum: 98,
        visitNum: 120
      };

      // 初始化图表
      this.initIncomeTrendChart();
      this.initRegisterChart();
      this.initVisitChart();
      this.initExpenseChart();
      this.updateStatCards();
    },

    // 生成默认日期数组
    generateDefaultDates(days) {
      const dates = [];
      const today = new Date();

      for (let i = days - 1; i >= 0; i--) {
        const date = new Date();
        date.setDate(today.getDate() - i);
        const month = date.getMonth() + 1;
        const day = date.getDate();
        dates.push(`${month}月${day}日`);
      }

      return dates;
    },


    // 初始化收入趋势图表（修改版）
    initIncomeTrendChart() {
      if (!this.$refs.incomeTrendChart) {
        console.warn('incomeTrendChart ref 未找到');
        return;
      }

      try {
        // 先销毁已存在的实例
        if (this.incomeTrendChart) {
          this.incomeTrendChart.dispose();
        }

        this.incomeTrendChart = echarts.init(this.$refs.incomeTrendChart);

        // 确保apiData存在且包含必要数据
        const incomeTrendData = this.apiData?.incomeTrend || {
          dates: this.generateDefaultDates(7),
          registerAmounts: [1200, 1400, 1000, 1600, 1800, 1500, 2000],
          chargeAmounts: [3200, 2800, 3500, 3000, 3800, 4200, 4000],
          westernAmounts: [1800, 1600, 2000, 2200, 2400, 2000, 2500],
          chineseAmounts: [800, 700, 900, 750, 850, 900, 950]
        };

        const option = {
          tooltip: {
            trigger: 'axis',
            formatter: function (params) {
              let result = params[0].axisValue + '<br/>';
              params.forEach(param => {
                result += `${param.seriesName}: ¥${param.value}<br/>`;
              });
              return result;
            }
          },
          legend: {
            data: ['挂号金额', '就诊收费金额', '西药处方金额', '中药处方金额'],
            bottom: 10
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            top: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: incomeTrendData.dates,
            axisLabel: {
              rotate: 45
            }
          },
          yAxis: {
            type: 'value',
            axisLabel: {
              formatter: '¥{value}'
            }
          },
          series: [
            {
              name: '挂号金额',
              type: 'line',
              data: incomeTrendData.registerAmounts,
              smooth: true,
              itemStyle: {color: '#67C23A'},
              lineStyle: {width: 3}
            },
            {
              name: '就诊收费金额',
              type: 'line',
              data: incomeTrendData.chargeAmounts,
              smooth: true,
              itemStyle: {color: '#E6A23C'},
              lineStyle: {width: 3}
            },
            {
              name: '西药处方金额',
              type: 'line',
              data: incomeTrendData.westernAmounts,
              smooth: true,
              itemStyle: {color: '#409EFF'},
              lineStyle: {width: 3}
            },
            {
              name: '中药处方金额',
              type: 'line',
              data: incomeTrendData.chineseAmounts,
              smooth: true,
              itemStyle: {color: '#B37FEB'},
              lineStyle: {width: 3}
            }
          ]
        };

        this.incomeTrendChart.setOption(option);
      } catch (error) {
        console.error('初始化收入趋势图表失败:', error);
      }
    },


    // 初始化挂号人次图表（修改版）
    initRegisterChart() {
      if (!this.$refs.registerChart) {
        console.warn('registerChart ref 未找到');
        return;
      }

      try {
        // 先销毁已存在的实例
        if (this.registerChart) {
          this.registerChart.dispose();
        }

        this.registerChart = echarts.init(this.$refs.registerChart);

        const registerData = this.apiData?.registerTrend || {
          dates: this.generateDefaultDates(7),
          appointmentCounts: [45, 50, 40, 55, 60, 50, 65],
          onsiteCounts: [30, 35, 25, 40, 45, 35, 50]
        };

        const option = {
          tooltip: {
            trigger: 'axis',
            formatter: function (params) {
              let result = params[0].axisValue + '<br/>';
              params.forEach(param => {
                result += `${param.seriesName}: ${param.value}人次<br/>`;
              });
              return result;
            }
          },
          legend: {
            data: ['预约挂号人次', '现场挂号人次'],
            bottom: 10
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            top: '10%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: registerData.dates,
            axisLabel: {
              rotate: 45
            }
          },
          yAxis: {
            type: 'value',
            name: '人次'
          },
          series: [
            {
              name: '预约挂号人次',
              type: 'bar',
              data: registerData.appointmentCounts,
              itemStyle: {color: '#409EFF'}
            },
            {
              name: '现场挂号人次',
              type: 'bar',
              data: registerData.onsiteCounts,
              itemStyle: {color: '#67C23A'}
            }
          ]
        };

        this.registerChart.setOption(option);
      } catch (error) {
        console.error('初始化挂号人次图表失败:', error);
      }
    },

    // 初始化就诊人次图表（修改版）
    initVisitChart() {
      if (!this.$refs.visitChart) {
        console.warn('visitChart ref 未找到');
        return;
      }

      try {
        // 先销毁已存在的实例
        if (this.visitChart) {
          this.visitChart.dispose();
        }

        this.visitChart = echarts.init(this.$refs.visitChart);

        const visitData = this.apiData?.visitTrend || {
          dates: this.generateDefaultDates(7),
          appointmentCounts: [40, 45, 35, 50, 55, 45, 60],
          onsiteCounts: [25, 30, 20, 35, 40, 30, 45]
        };

        const option = {
          tooltip: {
            trigger: 'axis',
            formatter: function (params) {
              let result = params[0].axisValue + '<br/>';
              params.forEach(param => {
                result += `${param.seriesName}: ${param.value}人次<br/>`;
              });
              return result;
            }
          },
          legend: {
            data: ['预约就诊人次', '现场就诊人次'],
            bottom: 10
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            top: '10%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: visitData.dates,
            axisLabel: {
              rotate: 45
            }
          },
          yAxis: {
            type: 'value',
            name: '人次'
          },
          series: [
            {
              name: '预约就诊人次',
              type: 'bar',
              data: visitData.appointmentCounts,
              itemStyle: {color: '#E6A23C'}
            },
            {
              name: '现场就诊人次',
              type: 'bar',
              data: visitData.onsiteCounts,
              itemStyle: {color: '#F56C6C'}
            }
          ]
        };

        this.visitChart.setOption(option);
      } catch (error) {
        console.error('初始化就诊人次图表失败:', error);
      }
    },


    // 初始化费用占比图表
    initExpenseChart() {
      if (!this.$refs.expenseChart) {
        console.warn('expenseChart ref 未找到');
        return;
      }

      try {
        // 先销毁已存在的实例
        if (this.expenseChart) {
          this.expenseChart.dispose();
        }

        this.expenseChart = echarts.init(this.$refs.expenseChart);

        const option = {
          tooltip: {trigger: 'item'},
          legend: {
            orient: 'vertical',
            right: 10,
            top: 'center'
          },
          series: [{
            name: '费用占比',
            type: 'pie',
            radius: ['40%', '70%'],
            data: [
              {
                value: this.apiData.expenseRatio?.registerFee || 0,
                name: '挂号费',
                itemStyle: {color: '#67C23A'}
              },
              {
                value: this.apiData.expenseRatio?.examFee || 0,
                name: '检查费',
                itemStyle: {color: '#409EFF'}
              },
              {
                value: this.apiData.expenseRatio?.treatmentFee || 0,
                name: '治疗费',
                itemStyle: {color: '#E6A23C'}
              },
              {
                value: this.apiData.expenseRatio?.westernMedicineFee || 0,
                name: '西药费',
                itemStyle: {color: '#B37FEB'}
              },
              {
                value: this.apiData.expenseRatio?.chineseMedicineFee || 0,
                name: '中药费',
                itemStyle: {color: '#F56C6C'}
              }
            ]
          }]
        };

        this.expenseChart.setOption(option);
      } catch (error) {
        console.error('初始化费用占比图表失败:', error);
      }
    },

    // 更新统计卡片数据
    // 在updateStatCards方法中更新为：
    updateStatCards() {
      if (!this.apiData) return;

      this.statCards = [
        {
          icon: 'el-icon-chargingPrice',
          title: '西药处方金额',
          value: `¥${this.apiData.drugRxMoney || '0'}`,
          color: '#409EFF'
        },
        {
          icon: 'el-icon-xy',
          title: '西药处方数量',
          value: this.apiData.drugRxNum || '0',
          color: '#67C23A'
        },
        {
          icon: 'el-icon-navicon-kcz',
          title: '挂号金额',
          value: `¥${this.apiData.regMoney || '0'}`,
          color: '#E6A23C'
        },
        {
          icon: 'el-icon-ghlb',
          title: '挂号人次',
          value: this.apiData.regNum || '0',
          color: '#F56C6C'
        },
        {
          icon: 'el-icon-tjxg',
          title: '处方金额',
          value: `¥${this.apiData.rxMoney || '0'}`,
          color: '#909399'
        },
        {
          icon: 'el-icon-charging',
          title: '处方数量',
          value: this.apiData.rxNum || '0',
          color: '#B37FEB'
        },
        {
          icon: 'el-icon-mzy',
          title: '中药处方金额',
          value: `¥${this.apiData.tcmRxMoney || '0'}`,
          color: '#B37FEB'
        },
        {
          icon: 'el-icon-ddzy',
          title: '中药处方数量',
          value: this.apiData.tcmRxNum || '0',
          color: '#909399'
        },
        {
          icon: 'el-icon-zhifubao',
          title: '就诊收费金额',
          value: `¥${this.apiData.visitChargeMoney || '0'}`,
          color: '#F56C6C'
        },
        {
          icon: 'el-icon-flxz',
          title: '就诊收费人次',
          value: this.apiData.visitChargeNum || '0',
          color: '#E6A23C'
        },
        {
          icon: 'el-icon-dangan',
          title: '就诊人次',
          value: this.apiData.visitNum || '0',
          color: '#67C23A'
        },
        {
          icon: 'el-icon-lcyt',
          title: '药占比',
          value: this.calculateMedicineRatio(),
          color: '#409EFF'
        }
      ];
    },

    // 计算药占比
    calculateMedicineRatio() {
      if (!this.apiData) return '0%';
      const total = this.apiData.visitChargeMoney || 0;
      const medicine = (this.apiData.drugRxMoney || 0) + (this.apiData.tcmRxMoney || 0);
      return total > 0 ? `${Math.round((medicine / total) * 100)}%` : '0%';
    },
    updateCurrentDateTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth() + 1;
      const date = now.getDate();
      const hours = now.getHours();
      const minutes = now.getMinutes().toString().padStart(2, '0');
      const seconds = now.getSeconds().toString().padStart(2, '0');

      const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
      const weekDay = weekDays[now.getDay()];

      this.currentDate = `${year}年${month}月${date}日 ${hours}:${minutes}:${seconds}`;
      this.currentWeekDay = weekDay;

      // 设置问候语
      this.setGreeting(hours);
    },

    initWeather() {
      // 这里应该是调用天气API获取数据，这里模拟数据
      const weatherTypes = [
        {type: 'sunny', icon: 'el-icon-sunny', text: '晴', temp: 28},
        {type: 'cloudy', icon: 'el-icon-cloudy', text: '多云', temp: 26},
        {type: 'rainy', icon: 'el-icon-umbrella', text: '小雨', temp: 22},
        {type: 'thunder', icon: 'el-icon-lightning', text: '雷阵雨', temp: 24},
        {type: 'fog', icon: 'el-icon-heavy-rain', text: '雾', temp: 20}
      ];

      // 随机选择一种天气（实际应用中应该调用API获取真实数据）
      const randomWeather = weatherTypes[Math.floor(Math.random() * weatherTypes.length)];
      this.weatherInfo = randomWeather;
    },
    setGreeting(hours) {
      const userInfo = JSON.parse(localStorage.getItem('userInfo')) || {};
      const staffName = userInfo.staffName || '医生';

      if (hours >= 5 && hours < 9) {
        this.greeting = `早上好，${staffName}`;
      } else if (hours >= 9 && hours < 12) {
        this.greeting = `上午好，${staffName}`;
      } else if (hours >= 12 && hours < 14) {
        this.greeting = `中午好，${staffName}`;
      } else if (hours >= 14 && hours < 18) {
        this.greeting = `下午好，${staffName}`;
      } else if (hours >= 18 && hours < 23) {
        this.greeting = `晚上好，${staffName}`;
      } else {
        this.greeting = `凌晨了，该休息了，${staffName}，`;
      }
    },
    initCharts() {
      // 收入趋势折线图
      this.incomeTrendChart = echarts.init(this.$refs.incomeTrendChart);
      this.incomeTrendChart.setOption({
        title: {
          text: '',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['挂号金额', '就诊收费金额', '西药处方金额', '中药处方金额'],
          bottom: 10
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['3月1日', '3月2日', '3月3日', '3月4日', '3月5日', '3月6日', '3月7日']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '挂号金额',
            type: 'line',
            smooth: true,
            data: [1200, 1400, 1000, 1600, 1800, 1500, 2000],
            itemStyle: {
              color: '#67C23A'
            }
          },
          {
            name: '就诊收费金额',
            type: 'line',
            smooth: true,
            data: [3200, 2800, 3500, 3000, 3800, 4200, 4000],
            itemStyle: {
              color: '#E6A23C'
            }
          },
          {
            name: '西药处方金额',
            type: 'line',
            smooth: true,
            data: [1800, 1600, 2000, 2200, 2400, 2000, 2500],
            itemStyle: {
              color: '#409EFF'
            }
          },
          {
            name: '中药处方金额',
            type: 'line',
            smooth: true,
            data: [800, 700, 900, 750, 850, 900, 950],
            itemStyle: {
              color: '#B37FEB'
            }
          }
        ]
      });

      // 挂号人次柱状图
      this.registerChart = echarts.init(this.$refs.registerChart);
      this.registerChart.setOption({
        title: {
          text: '',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['预约挂号人次', '现场挂号人次'],
          bottom: 10
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['3月1日', '3月2日', '3月3日', '3月4日', '3月5日', '3月6日', '3月7日']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '预约挂号人次',
            type: 'bar',
            data: [45, 50, 40, 55, 60, 50, 65],
            itemStyle: {
              color: '#409EFF'
            }
          },
          {
            name: '现场挂号人次',
            type: 'bar',
            data: [30, 35, 25, 40, 45, 35, 50],
            itemStyle: {
              color: '#67C23A'
            }
          }
        ]
      });

      // 就诊人次柱状图
      this.visitChart = echarts.init(this.$refs.visitChart);
      this.visitChart.setOption({
        title: {
          text: '',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['预约就诊人次', '现场就诊人次'],
          bottom: 10
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['3月1日', '3月2日', '3月3日', '3月4日', '3月5日', '3月6日', '3月7日']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '预约就诊人次',
            type: 'bar',
            data: [40, 45, 35, 50, 55, 45, 60],
            itemStyle: {
              color: '#E6A23C'
            }
          },
          {
            name: '现场就诊人次',
            type: 'bar',
            data: [25, 30, 20, 35, 40, 30, 45],
            itemStyle: {
              color: '#F56C6C'
            }
          }
        ]
      });

      // 费用占比饼图
      this.expenseChart = echarts.init(this.$refs.expenseChart);
      this.expenseChart.setOption({
        title: {
          text: '',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center'
        },
        series: [
          {
            name: '费用占比',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              {value: 35, name: '挂号费', itemStyle: {color: '#67C23A'}},
              {value: 25, name: '检查费', itemStyle: {color: '#409EFF'}},
              {value: 20, name: '治疗费', itemStyle: {color: '#E6A23C'}},
              {value: 15, name: '西药费', itemStyle: {color: '#B37FEB'}},
              {value: 5, name: '中药费', itemStyle: {color: '#F56C6C'}}
            ]
          }
        ]
      });
    },

    handleResize() {
      [this.incomeTrendChart, this.registerChart, this.visitChart, this.expenseChart].forEach(chart => {
        try {
          chart?.resize();
        } catch (error) {
          console.error('调整图表大小失败:', error);
        }
      });
    }

  }
};
</script>

<style lang="less" scoped>
/* 卡片基础样式 */
.stat-card {
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fff; /* 默认白色背景 */
  border: 1px solid #ebeef5; /* 轻微边框 */
}

/* 鼠标悬停时：背景变亮 + 上浮 + 阴影 */
.stat-card:hover {
  background: #84bdf5; /* 更亮的背景色 */
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1); /* 更明显的阴影 */
  border-color: #dcdfe6; /* 边框加深 */
}

/* 图标悬停动画 */
.card-icon i {
  transition: all 0.3s ease;
}

.stat-card:hover .card-icon i {
  transform: scale(1.1);
  color: white; /* 保持图标颜色 */
}

/* 卡片内容文字悬停效果（可选） */
.stat-card:hover .card-title {
  color: #333; /* 标题变深 */
}

.stat-card:hover .card-value {
  color: #409EFF; /* 数值变主题色 */
}

/deep/ .el-calendar-table .el-calendar-day {
  font-size: 10px;
  padding: 0;
  height: 38px;
  width: 100%;
}

.dashboard-container {
  display: flex;
  height: 100vh;
  padding: 20px;
  // background-color: #f5f7fa;

  .left-container {
    width: 350px;
    margin-right: 20px;

    .left-top {
      display: flex;
      flex-direction: column;
      height: 100%;

      .left-top-header {
        display: flex;
        padding-bottom: 12px;

        .clinic-logo {
          width: 68px;
          height: 68px;
          margin-right: 15px;

          img {
            width: 100%;
            height: 100%;
            border-radius: 8px;
            object-fit: cover;
          }
        }

        .current-time {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: center;

          .time-weather {
            display: flex;
            align-items: center;
            margin-bottom: 5px;

            .date {
              font-size: 14px;
              font-weight: bold;
              margin-right: 15px;
            }

            .weather {
              display: flex;
              align-items: center;
              font-size: 14px;

              i {
                margin-right: 5px;
                font-size: 18px;
                color: #E6A23C; // 晴天黄色，其他天气可以根据实际调整
              }
            }
          }

          .greeting {
            font-size: 16px;
            color: #409EFF;
            font-weight: bold;
          }
        }
      }

      .left-top-bottom {
        flex: 1;
        display: flex;
        flex-direction: column;

        .clinic-info-card {
          margin-bottom: 20px;

          .info-item {
            margin-bottom: 10px;
            font-size: 14px;

            &:last-child {
              margin-bottom: 0;
            }

            .label {
              font-weight: bold;
              color: #606266;
            }

            .value {
              color: #303133;
            }
          }
        }

        .calendar-container {
          background-color: #fff;
          border-radius: 4px;
          padding: 10px;
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

          .calendar-header {
            text-align: center;
            font-weight: bold;
            margin-bottom: 10px;
            color: #303133;
          }

          // 添加样式
          .calendar-container {
            .calendar-header {
              display: flex;
              flex-direction: column;
              margin-bottom: 10px;

              .date-range-selector {
                margin-bottom: 10px;

                /deep/ .el-range-editor.el-input__inner {
                  width: 100%;
                }
              }
            }

            // 其他样式...
          }

          .calendar-week {
            display: flex;
            margin-bottom: 10px;

            .week-day {
              flex: 1;
              text-align: center;
              font-size: 12px;
              color: #909399;
            }
          }

          .calendar-day {
            height: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            position: relative;

            &.is-signed {
              color: #67C23A;
              font-weight: bold;
            }

            .signed-icon {
              position: absolute;
              top: 2px;
              right: 2px;
              font-size: 14px;
              color: #67C23A;
            }
          }

          .calendar-days {
            display: flex;
            flex-wrap: wrap;

            .day {
              width: 14.28%;
              height: 40px;
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              font-size: 12px;
              position: relative;

              &.today {
                .day-number {
                  background-color: #409EFF;
                  color: #fff;
                  border-radius: 50%;
                  width: 24px;
                  height: 24px;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                }
              }

              &.other-month {
                .day-number {
                  color: #C0C4CC;
                }
              }

              .day-number {
                margin-bottom: 2px;
              }

              .day-status {
                font-size: 10px;
                color: #67C23A;
              }
            }
          }
        }
      }
    }
  }

  .right-container {
    flex: 1;
    display: flex;
    flex-direction: column;

    .stats-cards {
      display: grid;
      grid-template-columns: repeat(6, 1fr);
      gap: 4px;
      margin-bottom: 6px;

      .stat-card {
        opacity: 0;
        animation: fadeIn 0.5s forwards;
        display: flex;
        align-items: center;
        padding: 4px;

        .df {
          display: flex;

          .card-icon {
            width: 40px;
            height: 40px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 8px;

            i {
              font-size: 18px;
              color: #fff;
            }
          }

          .card-content {
            .card-title {
              font-size: 12px;
              color: #909399;
              margin-bottom: 4px;
            }

            .card-value {
              font-size: 14px;
              font-weight: bold;
              color: #303133;
            }
          }
        }

      }
    }

    .chart-container {
      margin-bottom: 20px;

      .chart-card {
        padding: 8px;

        .chart-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 15px;

          .chart-title {
            font-size: 16px;
            font-weight: bold;
            color: #303133;
          }
        }

        .chart-wrapper {
          width: 100%;

          .chart {
            width: 100%;
          }
        }
      }
    }

    .double-chart-container {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 15px;
      margin-bottom: 20px;

      .half-chart-card {
        padding: 15px;

        .chart-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 15px;

          .chart-title {
            font-size: 16px;
            font-weight: bold;
            color: #303133;
          }
        }

        .chart-wrapper {
          width: 100%;

          .chart {
            width: 100%;
          }
        }
      }
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>